package com.omronble.bp_broadcast.activity;

import androidx.appcompat.app.AlertDialog;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;

import com.google.gson.Gson;
import com.huawei.hmf.tasks.Task;
import com.huawei.hms.common.ApiException;
import com.huawei.hms.common.ResolvableApiException;
import com.huawei.hms.location.FusedLocationProviderClient;
import com.huawei.hms.location.LocationAvailability;
import com.huawei.hms.location.LocationCallback;
import com.huawei.hms.location.LocationRequest;
import com.huawei.hms.location.LocationResult;
import com.huawei.hms.location.LocationServices;
import com.huawei.hms.location.LocationSettingsRequest;
import com.huawei.hms.location.LocationSettingsResponse;
import com.huawei.hms.location.LocationSettingsStatusCodes;
import com.huawei.hms.location.SettingsClient;
import com.jaeger.library.StatusBarUtil;
import com.omronble.bp_broadcast.tools.Constants;
import com.omronble.bp_broadcast.R;
import com.omronble.bp_broadcast.bean.UpdateBean;
import com.omronble.bp_broadcast.tools.DeviceMethod;
import com.omronble.bp_broadcast.tools.Utils;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.List;

import io.reactivex.Observable;
import okhttp3.Call;

public class LoadingActivity extends BaseActivity {

    private String TAG = this.getClass().getSimpleName();private SharedPreferences mSharedPreferences;
    private Handler handler ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading);
        StatusBarUtil.setColor(this, Color.parseColor("#0099CC"));
        Log.d(TAG,"...onCreate");
        handler = new Handler();
        mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        initLocation();
        checkLocationPermission();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if ( DeviceMethod.getInstance(this).isActivated() ) {
            initAllPermissions();
        } else
            handler.postDelayed(() -> DeviceMethod.getInstance(this).onActivate(),1000);
    }

    private AlertDialog alertDialog;
    private void initAllPermissions(){
        if ( alertDialog != null && alertDialog.isShowing() )
            return;
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        Observable<Boolean> observable;
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P)
            observable = permissions.request(Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION);
        else
            observable = permissions.request(Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_BACKGROUND_LOCATION);
        observable.subscribe( granted -> {
            if ( granted )
                getApkUpdate();
            else {
                if ( alertDialog == null ) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(LoadingActivity.this);
                    builder.setTitle("提示");
                    builder.setMessage("有必需的权限没有打开，是否现在打开！");
                    builder.setCancelable(false);
                    builder.setPositiveButton("跳转", (dialog, which) -> {
                        getAppDetailSettingIntent();
                        dialog.dismiss();
                    });
                    builder.setNegativeButton("取消", (dialog, which) -> {
                    handler.postDelayed(() -> initAllPermissions(),250);
                        dialog.dismiss();
                    });
                    alertDialog = builder.create();
                }
                alertDialog.show();
                Button btnPos = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
                Button btnNeg = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
                btnPos.setTextColor(Color.RED);
                btnNeg.setTextColor(Color.RED);
            }
        });
    }

    /**
     * 跳转到权限设置界面
     */
    private void getAppDetailSettingIntent(){
        Intent mIntent = new Intent();
        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            mIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            mIntent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            mIntent.setAction(Intent.ACTION_VIEW);
            mIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
            mIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        startActivity(mIntent);
    }

    private void init() {
        SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        String deviceId = mSharedPreferences.getString(Constants.deviceId,null);
        if ( TextUtils.isEmpty(deviceId) ) { //首次启动
            if ( !Utils.isNetworkConnected(this) ) {
                Intent intent = new Intent();
                intent.setAction("android.net.wifi.PICK_WIFI_NETWORK");
                startActivity(intent);
            } else {
                Utils.enableBlueTooth();
                startActivity(new Intent(this,GuideActivity.class));
            }
        } else {
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
    }

    private void getApkUpdate() {
        OkHttpUtils.post()
                .url(Constants.UPDATE_APK).build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e( "LoadingActivity>>> " , e == null ? "onError" : e.getLocalizedMessage() );
                        handler.postDelayed(() -> init(),500);
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        Log.d( "LoadingActivity>>> " , response );
                        UpdateBean bean = new Gson().fromJson(response,UpdateBean.class);
                        if ( bean.getClientVersionCode() <= Utils.getAppVersionCode(LoadingActivity.this) ) {
                            handler.postDelayed(() -> init(),500);
                        } else {  //can update
                            if ( !"must".equalsIgnoreCase(bean.getUpdateType()) ) {
                                AlertDialog.Builder builder = new AlertDialog.Builder(LoadingActivity.this);
                                builder.setTitle("提示");
                                builder.setMessage("有新的更新，是否现在更新！");
                                builder.setCancelable(false);
                                builder.setPositiveButton("是", (dialog, which) -> {
                                    Intent intent = new Intent(LoadingActivity.this,UpdateActivity.class);
                                    intent.putExtra("UpdateBean",bean );
                                    startActivity(intent);
                                    dialog.dismiss();
                                });
                                builder.setNegativeButton("否", (dialogInterface, i) -> {
                                    handler.postDelayed(() -> init(),500);
                                    dialogInterface.dismiss();
                                });
                                AlertDialog alertDialog = builder.create();
                                alertDialog.show();
                                Button btnPos = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
                                Button btnNeg = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);
                                btnPos.setTextColor(Color.RED);
                                btnNeg.setTextColor(Color.RED);
                            } else {
                                Intent intent = new Intent(LoadingActivity.this,UpdateActivity.class);
                                intent.putExtra("UpdateBean",bean );
                                startActivity(intent);
                            }
                        }
                    }
                });
    }


    /*********************************华为定位*******http://tangfan.top/api/Az/Bp****************************/

    LocationCallback mLocationCallback;
    LocationRequest mLocationRequest;
    private FusedLocationProviderClient mFusedLocationProviderClient;
    private SettingsClient mSettingsClient;

    private void checkLocationPermission() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        Observable<Boolean> observable;
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P)
            observable = permissions.request(Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION);
        else
            observable = permissions.request(Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    "android.permission.ACCESS_BACKGROUND_LOCATION");
        observable.subscribe(aBoolean -> {
            if (aBoolean)
                requestLocationUpdatesWithCallback();
            else
                Toast.makeText(LoadingActivity.this, "没有定位权限。", Toast.LENGTH_SHORT).show();
        });
    }


    private void initLocation() {
        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        mSettingsClient = LocationServices.getSettingsClient(this);
        mLocationRequest = new LocationRequest();
        // Sets the interval for location update (unit: Millisecond)
        mLocationRequest.setInterval(5000);
        // Sets the priority
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        if (null == mLocationCallback) {
            mLocationCallback = new LocationCallback() {
                @Override
                public void onLocationResult(LocationResult locationResult) {
                    if (locationResult != null) {
                        List<Location> locations = locationResult.getLocations();
                        if (!locations.isEmpty()) {
                            for (Location location : locations) {
                                Log.i(TAG,
                                        "onLocationResult location[Longitude,Latitude,Accuracy]:" + location.getLongitude()
                                                + "," + location.getLatitude() + "," + location.getAccuracy());
                                mSharedPreferences.edit()
                                        .putFloat("Latitude", (float) location.getLatitude())
                                        .putFloat("Longitude", (float) location.getLongitude())
                                        .apply();

                                removeLocationUpdatesWithCallback();
                            }
                        }
                    }
                }

                @Override
                public void onLocationAvailability(LocationAvailability locationAvailability) {
                    if (locationAvailability != null) {
                        boolean flag = locationAvailability.isLocationAvailable();
                        Log.i(TAG, "onLocationAvailability isLocationAvailable:" + flag);
                    }
                }
            };
        }
    }

    private void requestLocationUpdatesWithCallback() {
        try {
            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
            builder.addLocationRequest(mLocationRequest);
            LocationSettingsRequest locationSettingsRequest = builder.build();
            // Before requesting location update, invoke checkLocationSettings to check device settings.
            Task<LocationSettingsResponse> locationSettingsResponseTask = mSettingsClient.checkLocationSettings(locationSettingsRequest);
            locationSettingsResponseTask.addOnSuccessListener(locationSettingsResponse -> {
                Log.i(TAG, "check location settings success");
                mFusedLocationProviderClient
                        .requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper())
                        .addOnSuccessListener(aVoid -> Log.i(TAG, "requestLocationUpdatesWithCallback onSuccess"))
                        .addOnFailureListener(e -> Log.e(TAG,
                                "requestLocationUpdatesWithCallback onFailure:" + e.getMessage()));
            })
                    .addOnFailureListener(e -> {
                        Log.e(TAG, "checkLocationSetting onFailure:" + e.getMessage());
                        int statusCode = ((ApiException) e).getStatusCode();
                        switch (statusCode) {
                            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                                try {
                                    //When the startResolutionForResult is invoked, a dialog box is displayed, asking you to open the corresponding permission.
                                    ResolvableApiException rae = (ResolvableApiException) e;
                                    rae.startResolutionForResult(LoadingActivity.this, 0);
                                } catch (IntentSender.SendIntentException sie) {
                                    Log.e(TAG, "PendingIntent unable to execute request.");
                                }
                                break;
                        }
                    });
        } catch (Exception e) {
            Log.e(TAG, "requestLocationUpdatesWithCallback exception:" + e.getMessage());
        }
    }

    private void removeLocationUpdatesWithCallback() {
        try {
            Task<Void> voidTask = mFusedLocationProviderClient.removeLocationUpdates(mLocationCallback);
            voidTask.addOnSuccessListener(aVoid -> Log.i(TAG, "removeLocationUpdatesWithCallback onSuccess"))
                    .addOnFailureListener(e -> Log.e(TAG, "removeLocationUpdatesWithCallback onFailure:" + e.getMessage()));
        } catch (Exception e) {
            Log.e(TAG, "removeLocationUpdatesWithCallback exception:" + e.getMessage());
        }
    }

    /************************************************************************/


}
